package com.jqsoft.launcher.activity.pregnantWomen;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.jqsoft.launcher.activity.WebViewActivity;
import com.jqsoft.launcher.activity.bean.PregnantWomenBean;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.gairui.NibpExample;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.DateTools;
import com.jqsoft.launcher.util.FileService;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.WebServiceUtils;
import com.jqsoft.launcher.util.XmlUtil;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PregnantWomenFollowUpActivity extends WebViewActivity implements
View.OnClickListener {

	PregnantWomenBean personInfo;
	UserLoginInfo info = UserLoginInfo.getInstances();
	String jsonstr = null;
	private int updateIndex=-1;
	private String sPersonID1;
	private String sNo1;//档案编号
	private String sname1;//姓名
	private String sCardNo1;//证件号码

	private String tiwen="0";
	private String xueya="0";
	@Override
	protected void initGui() {
		super.initGui();
		webView.loadUrl("file:///android_asset/ycf_followup_record.html");
		webView.addJavascriptInterface(new JSObject(), "contact");
	}

	@Override
	protected void initAction() {
		setGoBack();
	}

	@Override
	protected void initData() {
		setTitle("产后访视信息表");
		Intent intent = getIntent();
        Bundle bundle=intent.getExtras();
        if(bundle!=null){
         personInfo= (PregnantWomenBean) bundle.get("MPGuanLi_PersonInfo");
         jsonstr=bundle.getString("Tjdata");
         sPersonID1=bundle.getString("sPersonID");
         sNo1=bundle.getString("sNo");
         sname1=bundle.getString("sname");
         sCardNo1=bundle.getString("sCardNo");
         updateIndex=bundle.getInt("chakan");
        }
	}

	@Override
	public void onClick(View v) {
	}

	private final class JSObject {
		//初始化页面
		@JavascriptInterface
		public void getHtml() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try {
						Map<String, String> map = new HashMap<String, String>();
						map.put("PostpartumVisit_sBreast", "Breast"); //乳房
						map.put("PostpartumVisit_slyma", "slyma");//恶露
						map.put("FristPrenatalCheck_Uterine", "Uterine");//子宫
						map.put("PostpartumVisit_sWound", "Wound");//伤口
						map.put("FollowUpRecord_sClassification", "Classification");//分类
						map.put("PostpartumVisit_sGuidance", "Guidance");//指导
						map.put("FristPrenatalCheck_sReferral", "Referral");//转诊
						JSONObject jsonObj = CommonUtil.getAllDictionary(map);
						if (personInfo != null) {
						jsonObj.put("sName", personInfo.getsPersonName());  //页面回显孕妇姓名
						jsonObj.put("sNo", personInfo.getsNo());	        //页面回显档案号
						}
						jsonObj.put("dVisitTime", DateTools.getFormatStringByDF_YYYY_MM_DD(new Date()));//页面回显随访日期
						jsonObj.put("dNextCheckDate", DateTools.getFormatStringByDF_YYYY_MM_DD(DateTools.getNextMonthByDate(new Date(),3)));//页面显示下次随访日期
						jsonObj.put("sNextVisitingPlace", info.getsOrganizationName());//随访单位
						jsonObj.put("DoctorList", info.getJsonArrayDoctors());//回显随访医生列表
						jsonObj.put("sDoctorName", info.getsUserName());//随访医生
						String json = jsonObj.toString();
						JSONObject jsonObj2=null;
						if(jsonstr!=null){
						jsonstr = jsonstr.replace("\n", "");
						jsonstr = jsonstr.replace("\\n", "");
//						jsonstr = jsonstr.replace("\r", "");
					//	jsonObj2= new JSONObject(jsonstr);
						}
						// 初始化
						webView.loadUrl("javascript:showHtml('" + json + "','"+jsonstr+"')");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		//保存操作
		@SuppressWarnings("unused")
		@JavascriptInterface
		public void save(String uploadType,String sName,String sNo,String dVisitTime,String Temperature,String sHealth,String sPsychologicStatus,String BloodPressureL,String BloodPressureH,String sBreastCode,String sBreastAnomaly,
				String slymaCode,String slymaAnomaly,String sUterineCode,String sUterineAnomaly,String sWoundCode,String sWoundAnomaly,String sOther,String sClassificationCode,String sClassificationanomaly,
				String sGuidanceCode,String sGuidanceOther,String sReferralCode,String sReferralreason,String sRorganization,String dNextCheckDate,String sNextVisitingPlace,String sDoctorName,
				String iWeatherHealthEducation,String sWeatherHealthEducationContent,String BaoJianZhidaoContent,String BaoJianZhidaoContentCode){
			try {
				String gKey = CommonUtil.getUUID();
				final JSONObject jsonVistingInfo = new JSONObject();

				jsonVistingInfo.put("xueya", xueya);
				jsonVistingInfo.put("tiwen", tiwen);

				jsonVistingInfo.put("gKey", gKey);
				jsonVistingInfo.put("gPwomenInfoKey", personInfo.getgKey());//?
				jsonVistingInfo.put("sName", sName);
				if (personInfo != null) {
					jsonVistingInfo.put("sPersonID", personInfo.getsPersonID());
					jsonVistingInfo.put("sNo", personInfo.getsNo());
				} else {
					jsonVistingInfo.put("sPersonID", sPersonID1);
					jsonVistingInfo.put("sNo", sNo1);
				}
				jsonVistingInfo.put("dVisitTime", dVisitTime);
				jsonVistingInfo.put("Temperature", Temperature);//?数据类型可能有问题
				jsonVistingInfo.put("sHealth", sHealth);
				jsonVistingInfo.put("sPsychologicStatus", sPsychologicStatus);
				jsonVistingInfo.put("BloodPressureL", BloodPressureL);
				jsonVistingInfo.put("BloodPressureH", BloodPressureH);
				jsonVistingInfo.put("sBreast", "");
				jsonVistingInfo.put("sBreastCode", sBreastCode);
				jsonVistingInfo.put("sBreastAnomaly", sBreastAnomaly);
				jsonVistingInfo.put("slyma", "");
				jsonVistingInfo.put("slymaCode", slymaCode);
				jsonVistingInfo.put("slymaAnomaly", slymaAnomaly);
				jsonVistingInfo.put("sUterine", "");
				jsonVistingInfo.put("sUterineCode",sUterineCode);
				jsonVistingInfo.put("sUterineAnomaly",sUterineAnomaly);
				jsonVistingInfo.put("sWound","");
				jsonVistingInfo.put("sWoundCode",sWoundCode);
				jsonVistingInfo.put("sWoundAnomaly",sWoundAnomaly);
				jsonVistingInfo.put("sOther",sOther);
				jsonVistingInfo.put("sClassification","");
				jsonVistingInfo.put("sClassificationCode",sClassificationCode);
				jsonVistingInfo.put("sGuidance","");
				jsonVistingInfo.put("sGuidanceCode",sGuidanceCode);
				jsonVistingInfo.put("sGuidanceOther",sGuidanceOther);
				jsonVistingInfo.put("sClassificationanomaly",sClassificationanomaly);
				jsonVistingInfo.put("sReferral","");
				jsonVistingInfo.put("sReferralCode",sReferralCode);
				jsonVistingInfo.put("sReferralreason",sReferralreason);
				jsonVistingInfo.put("sRorganization",sRorganization);
				jsonVistingInfo.put("dNextCheckDate",dNextCheckDate);
				jsonVistingInfo.put("sDoctorName",sDoctorName);
				jsonVistingInfo.put("sDoctorCode","");
				jsonVistingInfo.put("sAreaCode",personInfo.getsAreaCode());
				jsonVistingInfo.put("sAreaName",personInfo.getsPersonName());
				jsonVistingInfo.put("sAddUser", info.getsLoginName());
				jsonVistingInfo.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date()));
				jsonVistingInfo.put("sUpdateUser", "");
				jsonVistingInfo.put("dUpdateTime", "");
				jsonVistingInfo.put("sDeleteUser", "");
				jsonVistingInfo.put("dDeleteTime", "");
				jsonVistingInfo.put("sInputDeptName", info.getsOrganizationName());
				jsonVistingInfo.put("sInputDeptCode", info.getsOrganizationKey());
				jsonVistingInfo.put("iState", 1);
				jsonVistingInfo.put("iWeatherHealthEducation", iWeatherHealthEducation);
				jsonVistingInfo.put("sWeatherHealthEducationContent", sWeatherHealthEducationContent);
				jsonVistingInfo.put("iVisitingTimes", 0);//?
				jsonVistingInfo.put("BaoJianZhidaoContent", BaoJianZhidaoContent);
				jsonVistingInfo.put("BaoJianZhidaoContentCode", BaoJianZhidaoContentCode);
				jsonVistingInfo.put("sVisitingPlaceCode", "");
				jsonVistingInfo.put("sNextVisitingPlace", sNextVisitingPlace);
				Log.i("benny", jsonVistingInfo.toString());
				if("2".equals(uploadType)){
					PregnantWomenFollowUpActivity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							try {
								boolean issuccess=false;
								if(updateIndex>=0&&personInfo==null){

									 issuccess=new FileService(act).updateFromRom(updateIndex,sPersonID1, sNo1, sname1, sCardNo1, "孕产妇保健随访", jsonVistingInfo.toString(), "append.txt");
								}else{
								 issuccess=new FileService(act).saveToRom(personInfo.getsPersonID(),personInfo.getsNo(),personInfo.getsPersonName(),personInfo.getsCardNo(), "孕产妇保健随访", jsonVistingInfo.toString(), "append.txt");
								}if(issuccess){
									MessageTools.showDialogOk(ctx, "保存成功！本次随访数据保存在本机，请到“离线设置”-“上传随访信息”中上传或者修改数据！");
								}else{
									 Toast.makeText(PregnantWomenFollowUpActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
								 }
							} catch (Exception e) {
								 Toast.makeText(PregnantWomenFollowUpActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}
						}});
				}else if(BphsConstants.isNetAvailable&&"1".equals(uploadType)){
				PregnantWomenFollowUpActivity.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						//创建了对话框的构造器
						Builder builder = new Builder(PregnantWomenFollowUpActivity.this);
						builder.setTitle("温馨提示");
						builder.setMessage("确定将本次随访数据提交至服务器吗？注意：提交后本条数据无法在平板上再次修改！");
						builder.setPositiveButton("确定", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								try {
								String methodName = BphsURL.getCommonPath("AddPostpartumVisiting_METHOD");
								String serviceURL = BphsURL.getCommonPath("AddPostpartumVisiting_URL");
//								String methodName = "AddPostpartumVisiting"; 
//								String serviceURL = "http://60.171.146.122:9098/WebService/Andrews/PregnancyInfoWebService.asmx";
								String result =	WebServiceUtils.requestByParams(methodName, jsonVistingInfo.toString(), serviceURL);
								if(StringUtils.isNotBlank(result)){
									JSONObject json = new JSONObject(result);
									 String sResult = json.getString("sSuccess");
									 if(sResult.equals("1")){
										 Toast.makeText(PregnantWomenFollowUpActivity.this, "保存完成！", Toast.LENGTH_SHORT).show();
									 }else{
										 Toast.makeText(PregnantWomenFollowUpActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
									 }
								}else{
									Toast.makeText(PregnantWomenFollowUpActivity.this, "远程服务器故障！", Toast.LENGTH_SHORT).show();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}}
						});
						builder.setNegativeButton("取消", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								// Toast.makeText(PregnantWomenFollowUpActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
							}
						});
						AlertDialog dialog =builder.create();
						dialog.setCancelable(false);
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
						
					}
					
					
				});}else{
					 Toast.makeText(PregnantWomenFollowUpActivity.this, "离线状态只能保存随访信息！", Toast.LENGTH_LONG).show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		//调用蓝牙接口返回xml数据
		@JavascriptInterface
				public void getXML(String type){
					switch (BphsConstants.deviceBranchType) {
					case 0:
					Intent intent = new Intent();
					// 通讯接口
					intent.setComponent(new ComponentName("com.example.uray.bluetooth.comm.app", "com.example.uray.bluetooth.comm.app.CommActivity"));
					// 参数配置接口
					//intent.setComponent(new ComponentName("com.example.uray.bluetooth.comm.app", "com.example.uray.bluetooth.comm.app.ConfigActivity"));
					intent.setAction(Intent.ACTION_VIEW);   
					if(type.equals("1")){ 
						startActivityForResult(intent, 1);  //获取体温
					}else{
						startActivityForResult(intent, 2);  //获取血压
					}
					break;
					case 1:	
						if ("1".equals(type)) {
							MessageTools.showDialogOk(ctx, "当前功能还未开通，请手动输入！"); //获取体温
//							startActivity(iNibp);
						} else if ("2".equals(type)) {
							Intent iNibp = new Intent(PregnantWomenFollowUpActivity.this,
									NibpExample.class);
							startActivityForResult(iNibp, 3); //获取血压
						}
						break;
					default:
						break;
					}
				}
	}
	
	// 解析蓝牙接口返回的XML格式的字符串
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
          super.onActivityResult(requestCode, resultCode, data); 
        if(requestCode == 1 && resultCode == RESULT_OK){
        	//获取体温
        	String sb = data.getStringExtra("return");
//        	StringBuffer sb = new StringBuffer(); 
//        	try {
//        	InputStream in = getResources().getAssets().open("c.xml");
//            byte[]  b = new byte[4096]; 
//            int n;
//            while ((n = in.read(b))!= -1){ 
//                sb.append(new String(b,0,n)); 
//            }
//            } catch (IOException e) {
//				e.printStackTrace();
//			}
        	String jsonStr =  XmlUtil.parseXml(sb);
//       	MessageTools.showDialogOk(ctx, "返回结果", sb);
//        	Toast.makeText(ctx, a, 1).show();
        	tiwen="1";
        	webView.loadUrl("javascript:showXML('" + jsonStr + "')");
        } 
        if(requestCode == 2 && resultCode == RESULT_OK){
        	//获取血压
        	String sb = data.getStringExtra("return");
//        	StringBuffer sb = new StringBuffer(); 
//        	try {
//        	InputStream in = getResources().getAssets().open("c.xml");
//            byte[]  b = new byte[4096]; 
//            int n;
//            while ((n = in.read(b))!= -1){ 
//                sb.append(new String(b,0,n)); 
//            }
//            } catch (IOException e) {
//				e.printStackTrace();
//			}
        	String jsonStr =  XmlUtil.parseXml(sb);
//       	MessageTools.showDialogOk(ctx, "返回结果", sb);
//        	Toast.makeText(ctx, a, 1).show();
        	xueya="1";
        	webView.loadUrl("javascript:showXML2('" + jsonStr + "')");
        } 
        if(requestCode == 3&&data!=null){
			// 获取血压值
			String jsonstr = data.getStringExtra("jsonstr");
			xueya="1";
			webView.loadUrl("javascript:showXML2('" + jsonstr + "')");
			
		}
    }
}
